var express = require('express');
var router = express.Router();
var {userModel,cartModel} = require('../database/model/clientModel')
var bcrypt = require('bcryptjs')
var salt = bcrypt.genSaltSync(10) //盐
var jwt = require('jsonwebtoken')
var secret = 'asdfasdfasdfas46546asdfasdf654a6sdfa' //私钥

router.post('/', function(req, res, next) { //注册接口
  console.log(req.body);
  let {username,password} = req.body
  userModel.find({username}).then(result=>{
    console.log(result);
    if(result.length){ //账号被占用
      res.send({
        code:100,
        msg:'账号已被占用'
      })
      return
    }
    let hash = bcrypt.hashSync(password,salt)
    // console.log(hash);
    new userModel({  //向数据库新增用户
      username,
      password:hash
    }).save().then(result=>{
      res.send({
        code:101,
        msg:'注册成功'
      })
    })

  })
});



// 登录
router.get('/', function(req, res, next) {
  // console.log(req.query);
  let {username,password} = req.query
  userModel.find({username}).then(result=>{
    if(!result.length){ //判断账号是否存在
      res.send({
        code:100,
        msg:'账号不存在，请注册'
      })
      return
    }
    let hash = result[0].password //得到用户的加密密码
    let bool = bcrypt.compareSync(password,hash) //密码比对
    if(!bool){
      res.send({
        code:102,
        msg:'密码错误，请重试'
      })
      return
    }
    let token = jwt.sign({
      time:Date.now(),  //签发时间
      // expire:1000*60*60*24*7
      expire:1000*60*60*2 // 有效时长
    },secret)
    let {username,avatar,phone,_id} = result[0]
    res.send({
      code:101,
      msg:'登录成功',
      data:{_id,username,avatar,phone,token}
    })
  })
});


const multer  = require('multer')

// 方法1:指定图片存放路径即可，无法设置图片后缀
// const upload = multer({ dest: 'public/images' }) 
// router.post('/upload',upload.single('avatar'),(req,res)=>{
//   console.log(req.file);
// })

// 方法2：自主定义存放路径、图片名称
const storage = multer.diskStorage({
  destination: function (req, file, cb) { //定义存放路径
    cb(null, 'public/images')
  },
  filename: function (req, file, cb) { //定义图片名称
    const name = Date.now() + Math.random().toString(36).substring(2)
    // console.log(file);
    let type = file.mimetype.split('/')[1] //提取图片后缀
    cb(null, `${name}.${type}`)
  }
})
const upload = multer({ storage: storage })
router.post('/upload',upload.single('avatar'),(req,res)=>{
  // console.log(req.file);
  res.send({
    code:1,
    msg:'上传成功',
    data:{
      url:`/images/${req.file.filename}`
    }
  })
})

router.put('/',(req,res)=>{  //更新用户信息
  console.log(req.body);
  let {_id,info} = req.body
  userModel.update({_id},info).then(result=>{
    res.send({
      code:101,
      msg:'更新成功'
    })
  })
})


router.post('/cart',(req,res)=>{  //添加购物车
  console.log(req.body);
  new cartModel(req.body).save().then(result=>{
    res.send({
      code:101,
      msg:'成功加入购物车'
    })
  })
})

router.get('/cart',(req,res)=>{  //加载购物车
  let {userid} = req.query
  cartModel.find({userid}).then(result=>{
    res.send({
      code:101,
      msg:'购物车加载成功',
      data:result
    })
  })
})

router.put('/cart',(req,res)=>{  //加载购物车
  let {_id,num} = req.body
  console.log(req.body);
  cartModel.update({_id},{num}).then(result=>{
    res.send({
      code:101,
      msg:'成功修改购物车数量',
    })
  })
})

module.exports = router;
